package com.xinyue.cross.server.server.handler;

import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerResponseHeader;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyEncodeHandler extends ChannelOutboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(NettyEncodeHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        try {
            GameServerMessageModel<GameServerResponseHeader> responseModel = (GameServerMessageModel<GameServerResponseHeader>) msg;
            GameServerResponseHeader header = responseModel.getHeader();
            int headerBuffSize = header.getHeaderTotalSize() + 4;
            ByteBuf byteBuf = Unpooled.buffer(headerBuffSize);
            int totalSize = headerBuffSize;
            if (responseModel.getBody() != null) {
                totalSize += responseModel.getBody().readableBytes();
            }
            byteBuf.writeInt(totalSize);
            header.write(byteBuf);
            if (responseModel.getBody() == null) {
                ctx.writeAndFlush(byteBuf, promise);
            } else {
                ByteBuf newBuf = Unpooled.wrappedBuffer(byteBuf, responseModel.getBody());
                ctx.writeAndFlush(newBuf, promise);
            }
            logger.debug("服务器返回消息,size: {} header <-- {}, body <-- {}", totalSize, header, responseModel.getBodyStr());
        } catch (Throwable e) {
            logger.error("服务器返回消息编码失败", e);
        }
    }

}
